package com.atguigu.aops;

import com.atguigu.annotations.RedisLimitAnnotation;
import com.atguigu.exception.RedisLimitException;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: shenhao
 * @CreatTime: 2024/11/4 21:40
 * @Version: 1.0
 * Redis+Lua脚本+aop+反射+自定义注解, 组成自定义的基础架构限流组件
 * 只要是高可用,迅速想到redis+lua脚本 高可用, 高并发下可以实时生效
 */
@Aspect
@Component
@Slf4j
public class RedisLimitAop {
    Object result = null;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private DefaultRedisScript<Long> redisScript;
    @PostConstruct
    public void init(){
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        //redisScript.setScriptText(buildLuaScript());
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Around("@annotation(com.atguigu.annotations.RedisLimitAnnotation)")
    public Object limitAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("----------around-------");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLimitAnnotation annotation = method.getAnnotation(RedisLimitAnnotation.class);
        if (annotation != null) {
            //获取注解中的key,当作redis中的key
            String key = annotation.key();
            //获取类名字
            //getDeclaringClass返回 Class 表示声明此对象所表示的方法的类或接口的对象 // getName返回此 Class 对象表示的类、接口或其他实体的名称。
            String className = method.getDeclaringClass().getName();
            String methodName = signature.getName();
            String limitKey = className + "#" + methodName + "#" + key;
            log.info(limitKey);
            if (!StringUtils.hasText(key)) {
                throw new RedisLimitException("it's danger, limitKey can't be empty");
            }
            long limit = annotation.permitsPerSecond();
            long expire = annotation.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);
            //这个方法的参数 脚本, keys列表, 可变参数args
            Long count = stringRedisTemplate.execute(
                    redisScript,
                    keys,
                    String.valueOf(limit),
                    String.valueOf(expire)
            );
            System.out.println("Access try count is " + count + "\t key=" + key);
            // 如果返回的count不是空,并且为0, 就是限流状态
            if (count != null && count == 0) {
                // 第一学历统招本科，愿意跟着阳哥学技术，需要内推或高阶java资料学习的同学发邮件zzyybs@126.com
                //throw new RedisLimitException(annotation.msg());
                return annotation.msg();
            }
        //上面的逻辑没有生效,代表没有限流, 那么需要放行方法
        }
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        System.out.println("----------around end-------");
        return result;
    }

    /**
     * 构建redis lua脚本,防御性编程，程序员自我保护，闲聊
     * 能用LuaScript，就不要用java拼装
     * @return
     */
    private String buildLuaScript(){
        StringBuilder luaScript = new StringBuilder();
        luaScript.append("local key = KEYS[1]");
        //获取ARGV内参数Limit
        luaScript.append("\nlocal limit = tonumber(ARGV[1])");
        //获取key的次数
        luaScript.append("\nlocal currentLimit = tonumber(redis.call('get',key) or '0')");
        luaScript.append("\nif currentLimit + 1 > limit then");
        luaScript.append("\nreturn 0");
        luaScript.append("\nelse");
        //自增长 1
        luaScript.append("\n redis.call('INCRBY', key, 1)");
        //设置过期时间
        luaScript.append("\nredis.call('EXPIRE', key, ARGV[2])");
        luaScript.append("\nreturn currentLimit + 1");
        luaScript.append("\nend");
        return luaScript.toString();
    }
}
